/**   
 * @Title: SsqAndDltMainThread.java 
 * @Package: com.esun.rabbit2.viewer.mainact.lotteryhallact 
 * @Description: 双色球,大乐透主界面刷新线程
 * @Author: Kuroky chengxt@500wan.com
 * @Date: 2011-7-5 下午02:26:19  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.lotteryhallact;

import java.util.Hashtable;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.DaletouInfo;
import com.esun.model.ShuangseqiuInfo;
import com.esun.rabbit2.communicaters.mainthread.ShuangseqiuTermInfoCommunicater;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.shiyixuanwu.TempData;
import com.esun.ui.R;
import com.esun.util.log.EDebug;

/**
 * @ClassName: ShuangseqiuMainThread
 * @Description: 双色球,大乐透主界面刷新线程
 * @Author: Kuroky chengxt@500wan.com
 * @Date: 2011-7-5 下午02:26:19
 * 
 */
public class SsqAndDltMainThread {

	private LinearLayout itemView;
	private String lotid;

	// 时间及期号显示textView
	private TextView tvShuangseqiuTime;
	private TextView tvShuangseqiuTerm;

	private ProgressBar pb;

	private Handler handler;

	private static final int GET_TERM_SUCCESS = 10001;
	private static final int GET_TERM_FAILED = 10002;

	private Hashtable<String, String> htTermInfo = new Hashtable<String, String>();

	// 双色球大乐透通讯线程
	private ShuangseqiuTermInfoCommunicater communicater = new ShuangseqiuTermInfoCommunicater();

	private MyTimeLeftTimeCount ticker;

	private boolean isCanbuy = false;
	private boolean isRunning = false;
	// 是否是第一次加载
	private boolean isFirstLoading = true;

	private Context context;

	public SsqAndDltMainThread(LinearLayout itemView, String lotid, Context c) {
		this.itemView = itemView;
		this.lotid = lotid;
		this.context = c;

		initHandler();
	}

	private void initHandler() {
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				switch (msg.what) {
				case GET_TERM_SUCCESS:
					isCanbuy = true;
					isRunning = false;
					EDebug.o(this, "期号获取成功");
					showInfoTermSuccess();

					break;

				case GET_TERM_FAILED:
					EDebug.o(this, "期号获取失败");
					isCanbuy = false;
					isRunning = false;

					// 获取服务器信息失败
					showInfoTermFail();
					break;

				default:
					break;
				}
			}
		};
	}

	/*
	 * 处理信息获取成功的时候具体哪些信息应该显示
	 */
	public void showInfoTermSuccess() {

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);

		// 今日开奖，显示剩余时间
		if (htTermInfo.get(Key.KEY_SHOWTYPE).equals(Config.NUM0)) {

			itemView.removeAllViews();
			itemView.addView(getLeftTimeView(), params);
			resetTicker();

			// 今日不开奖，显示截止时间
		} else {
			itemView.removeAllViews();
			itemView.addView(getEndTimeView(), params);
		}

		// 进度条消失
		pbGone();

	}

	/*
	 * 处理信息获取失败的时候具体哪些信息应该显示
	 */
	public void showInfoTermFail() {

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);

		itemView.removeAllViews();
		itemView.addView(getFailedView(), params);
		// 进度条消失
		pbGone();

	}

	/**
	 * @Title: showInfoStopLottery
	 * @Description: 返回猜中停售显示的View
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	public void showInfoStopLottery() {

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
		itemView.removeAllViews();
		itemView.addView(getStopLotteryView(), params);
		pbGone();
	}

	/*
	 * 刷新
	 */
	public void refresh() {

		if (!isRunning) {

			isCanbuy = false;

			// 第一次加载load页面
			if (isFirstLoading) {
				itemView.addView(getFailedView());
				isFirstLoading = false;
			}
			pbShow();

			// 获取期号及截止时间线程
			new Thread() {

				@Override
				public void run() {
					super.run();
					isRunning = true;
					// 获取期号及奖池信息
					if (!doGetTermInfo()) {
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
						}
					}
				}
			}.start();
		}
	}

	/*
	 * 获取期号及奖池信息
	 */
	private boolean doGetTermInfo() {

		if (communicater.getTermInfo(lotid)) {

			// 期号及剩余时间信息
			htTermInfo = communicater.getCurrentTermAndPool(lotid);
			EDebug.o(this, "@@@@@@@@@@@@@@@@@expect = " + htTermInfo.get(Key.KEY_EXPECT));
			Message msg = handler.obtainMessage(GET_TERM_SUCCESS);
			handler.sendMessage(msg);

			return true;
		} else {

			Message msg = handler.obtainMessage(GET_TERM_FAILED);
			handler.sendMessage(msg);
			return false;
		}
	}

	/*
	 * 计时器类
	 */
	private class MyTimeLeftTimeCount extends CountDownTimer {

		String strMin;
		String strSec;
		String strHour;
		long time;

		public MyTimeLeftTimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {

			time = millisUntilFinished / 1000;

			time = time % 86400;

			// 剩余小时
			strHour = String.valueOf(time / 3600);
			if (strHour.length() < 2) {
				strHour = TempData.NUM0 + strHour;
			}

			time = time % 3600;

			// 剩余分钟数
			strMin = String.valueOf(time / 60);
			if (strMin.length() < 2) {
				strMin = TempData.NUM0 + strMin;
			}

			// 剩余秒数
			strSec = String.valueOf(time % 60);
			if (strSec.length() < 2) {
				strSec = TempData.NUM0 + strSec;
			}

			// 2012-02-22 added by kuroky
			String strItem = strHour + Language.POPLOTTERYTIP_HOUR + strMin + Language.POPLOTTERYTIP_MINUTE + strSec + Language.POPLOTTERYTIP_SECOND;
			// 设置颜色
			SpannableString sp = new SpannableString(strItem);
			sp.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.gcdt_txt_term)), 0, strItem.indexOf(Language.POPLOTTERYTIP_XIAO), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			sp.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.gcdt_txt_term)), strItem.indexOf(Language.POPLOTTERYTIP_SHI) + 1,
					strItem.indexOf(Language.POPLOTTERYTIP_MINUTE), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			sp.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.gcdt_txt_term)), strItem.indexOf(Language.POPLOTTERYTIP_MINUTE) + 1,
					strItem.indexOf(Language.POPLOTTERYTIP_SECOND), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

			tvShuangseqiuTime.setText(sp);
		}

		@Override
		public void onFinish() {
			EDebug.o(this, "@@@@@@@@@@@@@@@@@expect = " + htTermInfo.get(Key.KEY_EXPECT));
			tvShuangseqiuTerm.setText(Language.POPLOTTERYTIP_DI + htTermInfo.get(TempData.EXPECT) + Language.POPLOTTERYTIP_QIYIJIEZHI);
			tvShuangseqiuTime.setText(Language.POPLOTTERYTIP_YUSHOU + communicater.getNexttTerm() + Language.POPLOTTERYTIP_QI);
			// 获取期号并存储
			if (lotid.equals(Config.SHUANGSEQIU)) {
				ShuangseqiuInfo.getShuangseqiuInfo().setTermNum(communicater.getNexttTerm());
			} else {
				DaletouInfo.getDaletouInfo().setTermNum(communicater.getNexttTerm());
			}

		}
	}

	private void resetTicker() {
		if (ticker != null) {
			ticker.cancel();
		}

		ticker = new MyTimeLeftTimeCount(Long.parseLong(htTermInfo.get(TempData.LEFT_TIME)) * 1000, 1000);
		ticker.start();
	}

	public boolean isCanbuy() {
		return this.isCanbuy;
	}

	/*
	 * 获取倒计时view
	 */
	private View getLeftTimeView() {

		LinearLayout llLeftTime = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.lottery_hall_left_time, null);

		// 时间
		TextView tvTime = (TextView) llLeftTime.findViewById(R.id.lotteryhall_act_tv_Time);
		// 期号
		TextView tvTerm = (TextView) llLeftTime.findViewById(R.id.lotteryhall_act_tv_Term_left_time);
		// 奖池
		TextView tvLotteryPool = (TextView) llLeftTime.findViewById(R.id.lottery_hall_tv_lottery_pool);
		// 加奖
		ImageView ivAddMoney = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_add_money_left_time);
		// 彩种logo
		ImageView ivLogo = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_logo_left_time);
		// 彩种名称logo
		ImageView ivNameLogo = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_name_logo_left_time);
		// 进度条
		pb = (ProgressBar) llLeftTime.findViewById(R.id.lotteryhall_act_pb_left_time);

		// 设置彩种及名称图标
		setLogo(ivLogo, ivNameLogo);

		// 奖池
		if (htTermInfo.get(Key.KEY_MONEY) != null && !htTermInfo.get(Key.KEY_MONEY).equals(Config.NULLMARK)) {
			String strShowLotteryPool = Language.POPLOTTERYTIP_LOTTERY_POOL + htTermInfo.get(Key.KEY_MONEY);
			tvLotteryPool.setTextColor(context.getResources().getColor(R.color.kjxx_red));
			tvLotteryPool.setText(strShowLotteryPool);
		} else {
			tvLotteryPool.setText(Language.TIP_SSQ_HOME_PAGE_INFO);
			tvLotteryPool.setTextColor(context.getResources().getColor(R.color.gcdt_txt_btn));
		}

		// 加奖
		if (htTermInfo.get(Key.KEY_ADDMONEY).equals(Config.NUM0) || htTermInfo.get(Key.KEY_ADDMONEY).equals(Config.NULLMARK)) {
			ivAddMoney.setVisibility(View.GONE);
		} else {
			ivAddMoney.setVisibility(View.VISIBLE);
		}

		// 期号
		String strShow = Language.POPLOTTERYTIP_JULI + htTermInfo.get(TempData.EXPECT) + Language.POPLOTTERYTIP_QIJIEZHI;
		tvTerm.setText(strShow);

		// 计时
		tvShuangseqiuTime = tvTime;
		tvShuangseqiuTerm = tvTerm;

		return llLeftTime;

	}

	/*
	 * 获取截止时间view
	 */
	private View getEndTimeView() {

		EDebug.o(this, "获取截止时间");

		LinearLayout llLeftTime = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.lottery_hall_lottery_pool, null);

		RelativeLayout rlTermAndPool = (RelativeLayout) llLeftTime.findViewById(R.id.lottery_hall_rl_dlt_jiezhi_time);
		// 期号
		TextView tvTerm = (TextView) llLeftTime.findViewById(R.id.lotteryhall_act_tv_Term);
		// 开奖信息
		TextView tvLotteryInfo = (TextView) llLeftTime.findViewById(R.id.lottery_hall_tv_lottery_msg);
		// 奖池
		TextView tvLotteryPool = (TextView) llLeftTime.findViewById(R.id.lotteryhall_act_tv_lottery_pool);
		// 加奖
		ImageView ivAddMoney = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_add_money);
		// 彩种logo
		ImageView ivLogo = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_logo);
		// 彩种名称logo
		ImageView ivNameLogo = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_name_logo);
		// 进度条
		pb = (ProgressBar) llLeftTime.findViewById(R.id.lotteryhall_act_pb_lottery_pool);

		// 设置彩种及名称图标
		setLogo(ivLogo, ivNameLogo);

		// 奖池
		if (htTermInfo.get(Key.KEY_MONEY) != null && !htTermInfo.get(Key.KEY_MONEY).equals(Config.NULLMARK)) {
			String strShowLotteryPool = Language.POPLOTTERYTIP_LOTTERY_POOL + htTermInfo.get(Key.KEY_MONEY);
			rlTermAndPool.setVisibility(View.VISIBLE);
			// 颜色设置
			SpannableString sp = new SpannableString(strShowLotteryPool);
			sp.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.gcdt_txt_term)), 0, strShowLotteryPool.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			tvLotteryPool.setText(sp);
		} else {
			rlTermAndPool.setVisibility(View.GONE);
		}

		// 期号
		String strShow = Language.POPLOTTERYTIP_DI + htTermInfo.get(TempData.EXPECT) + Language.POPLOTTERYTIP_QI;
		tvTerm.setText(strShow);
		// 双色球每周二、四、日晚21:30开奖
		if (lotid.equals(Config.SHUANGSEQIU)) {
			tvLotteryInfo.setText(Language.TIP_SSQ_HOME_PAGE_INFO);
		} else {
			tvLotteryInfo.setText(Language.TIP_DLT_HOME_PAGE_INFO);
		}

		// 加奖
		if (htTermInfo.get(Key.KEY_ADDMONEY).equals(Config.NUM0) || htTermInfo.get(Key.KEY_ADDMONEY).equals(Config.NULLMARK)) {
			ivAddMoney.setVisibility(View.GONE);
		} else {
			ivAddMoney.setVisibility(View.VISIBLE);
		}

		return llLeftTime;
	}

	/*
	 * 获取失败时view
	 */
	private View getFailedView() {

		LinearLayout llLeftTime = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.lottery_hall_ssq_load_fail, null);

		// 彩种logo
		ImageView ivLogo = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_logo_load_fail);
		// 彩种名称logo
		ImageView ivNameLogo = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_name_logo_load_fail);
		// 提示信息
		TextView tvNote = (TextView) llLeftTime.findViewById(R.id.lottery_hall_tv_load_fail);
		// 进度条
		pb = (ProgressBar) llLeftTime.findViewById(R.id.lotteryhall_act_pb_load_fail);

		if (lotid.equals(Config.SHUANGSEQIU)) {
			tvNote.setText(Language.TIP_SSQ_HOME_PAGE_INFO);
		} else {
			tvNote.setText(Language.TIP_DLT_HOME_PAGE_INFO);
		}

		// 设置彩种及名称图标
		setLogo(ivLogo, ivNameLogo);

		return llLeftTime;
	}

	/**
	 * @Title: getStopLotteryView
	 * @Description: 返回彩种停售的显示View
	 * @param: @return 设定文件
	 * @return: View 返回类型
	 * @throws
	 */
	private View getStopLotteryView() {
		LinearLayout llLeftTime = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.lottery_hall_ssq_load_fail, null);

		// 彩种logo
		ImageView ivLogo = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_logo_load_fail);
		// 彩种名称logo
		ImageView ivNameLogo = (ImageView) llLeftTime.findViewById(R.id.lottery_hall_iv_name_logo_load_fail);
		// 提示信息
		TextView tvNote = (TextView) llLeftTime.findViewById(R.id.lottery_hall_tv_load_fail);
		// 进度条
		pb = (ProgressBar) llLeftTime.findViewById(R.id.lotteryhall_act_pb_load_fail);

		tvNote.setText(Language.POPLOTTERYTIP_LOTTERY_STOP);

		// 设置彩种及名称图标
		setLogo(ivLogo, ivNameLogo);

		return llLeftTime;
	}

	/*
	 * 设置彩种及名称图标
	 */
	private void setLogo(ImageView ivLogo, ImageView ivNameLogo) {

		Drawable dLogo = null;
		Drawable dNameLogo = null;
		// 双色球
		if (lotid.equals(Config.SHUANGSEQIU)) {

			dLogo = context.getResources().getDrawable(R.drawable.img_default_boughtcenter_doubleball_53x53);
			dNameLogo = context.getResources().getDrawable(R.drawable.img_default_boughtcenter_doubleball_91x30);

			// 大乐透
		} else if (lotid.equals(Config.DALETOU)) {

			dLogo = context.getResources().getDrawable(R.drawable.img_default_boughtcenter_lotto_53x53);
			dNameLogo = context.getResources().getDrawable(R.drawable.img_default_boughtcenter_lotto_93x30);

		}

		// 设置彩种及名称图标
		ivLogo.setBackgroundDrawable(dLogo);
		ivNameLogo.setBackgroundDrawable(dNameLogo);
	}

	// 进度条显示
	public void pbShow() {
		if (pb != null) {
			pb.setVisibility(View.VISIBLE);
		}
	}

	// 进度条消失
	public void pbGone() {
		if (pb != null) {
			pb.setVisibility(View.GONE);
		}
	}

}
